/**
 * Created by 준영 on 14. 3. 28.
 */
var express = require('express');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);

var mongoDB = require('./database/mongoDB');
var redisDatabase = require('./database/redisDB');
var KeyValueStore = redisDatabase.KeyValueStore;
var RouteAPI = require('./routes/apis').RouteApi;

var AccountApi = require('./routes/accountApi').AccountApi;
var FreeboardApi = require('./routes/freeboardApi').FreeboardApi;
var FileIOApi = require('./routes/fileIOApi').FileIOApi;
var CommonApi =  require('./routes/commonApi').CommonApi;

var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');


var app = express();

var Middleware = require('./routes/middle').Middleware;


exports.Server = (function () {
    function Server(servicePort, mongoDbUrl, redisUrl) {
        this.mongoDbUrl = mongoDbUrl;
        this.redisUrl = redisUrl;
        this.port = servicePort;
    }


    Server.prototype.start = function (callback) {
        var self = this;


        mongoDB.connect(self.mongoDbUrl, function (err, database) {
            if (err) {

            }
            else {

                self.initApi(database);
                http.createServer(app).listen(self.port, function () {

                });
                /* database.db.collection('freeboard').find().toArray(function(err,res)
                 {

                 });*/
            }
        });

    };
    Server.prototype.initApi = function (database) {

        var self = this;
        var keyValueStore = new KeyValueStore(redisDatabase.createRedisClient(self.redisUrl));
        var sessionStore = new RedisStore({client: redisDatabase.createRedisClient(self.redisUrl)});

        var middle = new Middleware(keyValueStore, sessionStore);

        app.set('views', path.join(__dirname, 'views'));
        app.set('view engine', 'jade');

        app.use(express.cookieParser());
        app.use(express.session({
            store : sessionStore,
            key    : 'jsessionid',
            secret : 'Jogacsecret'
        }));

        app.use(express.favicon());
        app.use(express.logger('dev'));

        app.use(express.methodOverride());

        app.use(express.bodyParser({uploadDir: __dirname + '/tmp'}));

        app.use(express.static(path.join(__dirname, 'public')));


        app.use(express.json());
        app.use(express.urlencoded());
      app.use(express.bodyParser());



        app.use(express.cookieParser('shhhh, very secret'));
        app.use(express.session());

        app.use(middle.checkMobile());
        app.locals.pretty = true;
        app.use(app.router);
// development only
        if ('development' == app.get('env')) {
            app.use(express.errorHandler());
        }


        app.get('/', routes.index);
        app.get('/users', user.list);

        app.get('/login', routes.login);
        app.get('/freeboard', middle.needs(['auth']), routes.freeboard);
        app.get('/message', middle.needs(['auth']), routes.message)
        app.get('/test', routes.test);


        var routeAPI = new RouteAPI(database, keyValueStore, sessionStore);
        var AccountAPI =  new AccountApi(database, keyValueStore, sessionStore );
        var FreeboardAPI = new FreeboardApi(database,keyValueStore, sessionStore );

        var CommonAPI = new CommonApi(database, keyValueStore, sessionStore);

        var FileIOAPI = new FileIOApi(database, keyValueStore, sessionStore);

        app.post('/api/fileUpload', invoke(FileIOAPI, 'fileUpload'));
        app.post('/api/writeFreeboard', invoke(FreeboardAPI, 'writeFreeboard'));
        app.get('/api/getFreeboardList', invoke(FreeboardAPI, 'getFreeboardList'));
        app.get('/api/getTotalCount', invoke(FreeboardAPI, 'getTotalCount'));

        app.get('/api/alreadyUserCheck', invoke(AccountAPI, 'alreadyUserCheck'));
        app.post('/api/createUser', invoke(AccountAPI, 'createUser'));
        app.get('/api/CheckAuth', invoke(AccountAPI, 'CheckAuth'));
        app.get('/api/logout', invoke(AccountAPI, 'logout'));

        app.get('/api/getPrevAndNextItemIndex', invoke(FreeboardAPI, 'getPrevAndNextItemIndex') );
        app.post('/api/createComment', invoke(FreeboardAPI, 'createComment'));
        app.post('/api/deleteFreeboardItem', invoke(FreeboardAPI, 'deleteFreeboardItem'));
        app.post('/api/modifyFreeboardItem', invoke(FreeboardAPI, 'modifyFreeboardItem'));

        app.get('/api/getMessageInfo', invoke(CommonAPI, 'getMessageInfo'));
        app.post('/api/sendMessage', invoke(CommonAPI, 'sendMessage'));

        app.get('/api/getMessageCount', invoke(CommonAPI, 'getMessageCount'));
        app.post('/api/deleteMessage',invoke(CommonAPI, 'deleteMessage'))


    };
    return Server;
})();

function invoke(obj, methodName) {
    return function () {
        obj[methodName].apply(obj, arguments);
    };
}